<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 17/12/26
 * Time: 11:27
 */

class PriorModel
{
    public function myAction($user,$page,$number=PAGE_NUMBER)
    {
        $data['lists'] = Db::name('live_list')
            ->field('id as llid,name,date,left(start_time,5) as start_time,left(end_time,5) as end_time,volume,enrol')
            ->where(['fid'=>$user['fid'],'udid'=>$user['id'],'status'=>['in','1,3']])
            ->page($page,$number)
            ->order('id desc')
            ->select();
        $data['page'] = $page;
        $data['count'] = Db::name('live_list')->where(['fid'=>$user['fid'],'udid'=>$user['id'],'status'=>['in','1,3']])->count();
        return $data;
    }

    public function issueAction($user,$page,$number=PAGE_NUMBER)
    {
        $data['lists'] = Db::name('live_list')
            ->field('ll.id as llid,ll.name,ll.date,left(ll.start_time,5) as start_time,left(ll.end_time,5) as end_time,if(ll.password,1,0) as password,ll.volume,ll.viewing,ll.enrol,ll.status,ud.nickname,ud.avatar')->alias('ll')
            ->join('users_detail ud','ll.udid = ud.id')
            ->where(['ll.fid'=>$user['fid'],'ll.udid'=>$user['id'],'ll.status'=>['in','9']])
            ->page($page,$number)
            ->order('ll.id desc')
            ->select();
        $data['page'] = $page;
        $data['count'] = Db::name('live_list')->where(['fid'=>$user['fid'],'udid'=>$user['id'],'status'=>['in','9']])->count();
        return $data;
    }

    public function waitAction($user,$page,$number=PAGE_NUMBER)
    {
        $data['lists'] = Db::name('live_list')
            ->field('ll.id as llid,ll.name,ll.date,left(ll.start_time,5) as start_time,left(ll.end_time,5) as end_time,ll.status,ll.volume,ll.click,ll.enrol,ud.nickname,ud.avatar')->alias('ll')
            ->join('users_detail ud','ll.udid = ud.id')
            ->join('enroll e','ll.id = e.follow AND e.status = 1 AND e.udid = '.$user['id'])
            ->where(['ll.fid'=>$user['fid'],'ll.status'=>['in','1,2']])
            ->page($page,$number)
            ->order('ll.id desc')
            ->select();
        $data['page'] = $page;
        $data['count'] = Db::name('live_list')->alias('ll')
            ->join('enroll e','ll.id = e.follow AND e.status = 1 AND e.udid = '.$user['id'])
            ->where(['ll.fid'=>$user['fid'],'ll.status'=>['in','1,2']])
            ->count();
        return $data;
    }

    public function endAction($user,$page,$number=PAGE_NUMBER)
    {
        $data['lists'] = Db::name('live_list')
            ->field('ll.id as llid,ll.name,ll.date,left(ll.start_time,5) as start_time,left(ll.end_time,5) as end_time,ll.password,ll.volume,ll.viewing,100 as score,ud.nickname,ud.avatar')->alias('ll')
            ->join('users_detail ud','ll.udid = ud.id')
            ->join('enroll e','ll.id = e.follow AND e.status = 1 AND e.udid = '.$user['id'])
            ->where(['ll.fid'=>$user['fid'],'ll.status'=>9])
            ->page($page,$number)
            ->order('ll.id desc')
            ->select();
        $data['page'] = $page;
        $data['count'] = Db::name('live_list')->alias('ll')
            ->join('enroll e','ll.id = e.follow AND e.status = 1 AND e.udid = '.$user['id'])
            ->where(['ll.fid'=>$user['fid'],'ll.status'=>9])
            ->count();
        return $data;
    }

    public function addPostAction($data,$user)
    {
        $data['udid']=$user['id'];
        $data['firm']=$user['firm'];
        $data['fid']=$user['fid'];
        $data['vid'] = 0;
        $data['channel']=$user['firm'].'-'.dechex(strtotime($data['date'].' '.$data['start_time']));
        $data['status']=1;
        $userId = explode(',',$data['notify']);
        $data['enrol'] = count($userId);
        $filePath = [];
        if(!empty($data['path']) && !empty($data['file'])){
            $path = $data['path'];
            $file = $data['file'];
            if($path && $file) {
                $path = json_decode($path,true);
                $file = json_decode($file,true);
                if (count($path) && count($file)) {
                    foreach ($path as $k => $v) {
                        $model = new ModelModel;
                        $filePath[$k] = $model->moveImg($v, $file[$k], 3);
                    }
                }
            }
        }
        unset($data['path']);
        unset($data['file']);
        $data['annex'] = json_encode($filePath);
        unset($data['token']);
        $data['phone']='';
        $llid = Db::name('live_list')->insertGetId($data);

        if(!empty($userId[0])){
            $add = [];
            foreach ($userId as $k => $v){
                $add[$k]['udid'] = $v;
                $add[$k]['firm'] = $user['firm'];
                $add[$k]['fid'] = $user['fid'];
                $add[$k]['follow'] = $llid;
                $add[$k]['status'] = 1;
            }
            Db::name('enroll')->insertAll($add);
            $msg['content'] ='Live training新培训通知！ 培训名称：'.$data['name'].'；培训时间：'.$data['date'].' '.substr($data['start_time'],0,5).'-'.substr($data['end_time'],0,5).'；请您准时参加！';
            $time = strtotime($data['date'].' '.substr($data['start_time'],0,5)) - 1800;
            $redis = Yaf_Registry::get('redis');
            $redis->hset('Push',$time, json_encode(['users'=>$data['notify'],'llid'=>$llid]));
        }
        $msg['message'] = '创建成功';
        return $msg;
    }

    public function editAction($llid,$user)
    {
        $data['live'] = Db::name('live_list')
            ->field('
            ll.id as llid,
            ll.name,
            ll.date,
            left(ll.start_time,5) as start_time,
            left(ll.end_time,5) as end_time,
            ll.password,
            ll.share,
            ll.view,
            ll.section,
            ll.notify,
            ll.number,
            ll.volume,
            ll.introduction,
            ll.gid,
            ll.bid,
            ll.annex,
            ifnull(b.image,"") as bimage
            ')->alias('ll')
            ->join('backdrop b','ll.bid = b.id','LEFT')
            ->where(['ll.id'=>$llid,'ll.udid'=>$user['id'],'ll.status'=>['in','1,3']])
            ->find();
        $annex = json_decode($data['live']['annex'],true);
        if($annex){
            $data['live']['annex']=array_slice($annex, 0, 9);
        }else{
            $data['live']['annex']=[];
        }
        $data['users'] = Db::name('users_detail')
            ->field('id as udid,nickname,phone')
            ->where(['id'=>['in',$data['live']['notify']]])
            ->select();
        $data['question'] = Db::name('question')
            ->where(['udid'=>$user['id'],'fid'=>$user['fid'],'llid'=>$llid,'status'=>1])
            ->count();
        return $data;
    }

    public function editPostAction($data,$user)
    {
        $llid = $data['llid'];
        unset($data['llid']);
        $live = Db::name('live_list')
            ->field('notify,annex')
            ->where(['id'=>$llid,'udid'=>$user['id'],'status'=>['in','1,3']])
            ->find();
        $userDec = explode(',',$live['notify']);
        $userInc = explode(',',$data['notify']);
        if($userDec[0]){
            $decNotify = count($userDec);
            Db::name('live_list')
                ->where('id',$llid)
                ->dec('number',$decNotify)
                ->setDec('enrol',$decNotify);
            $where['udid'] = ['in',$live['notify']];
            $where['fid'] = $user['fid'];
            $where['follow'] = $llid;
            Db::name('enroll')
                ->where($where)
                ->setField('status', 2);
        }
        if($userInc[0]){
            $incNotify = count($userInc);
            Db::name('live_list')
                ->where('id',$llid)
                ->inc('number',$incNotify)
                ->setInc('enrol',$incNotify);
            $notify = implode(',',array_intersect($userDec,$userInc));
            $where['udid'] = ['in',$notify];
            $where['fid'] = $user['fid'];
            $where['follow'] = $llid;
            Db::name('enroll')
                ->where($where)
                ->setField('status', 1);
            $add = [];
            $diff = array_diff($userInc,$userDec);
            foreach ($diff as $k => $v){
                $add[$k]['udid'] = $v;
                $add[$k]['firm'] = $user['firm'];
                $add[$k]['fid'] = $user['fid'];
                $add[$k]['follow'] = $llid;
                $add[$k]['status'] = 1;
            }
            Db::name('enroll')->insertAll($add);
            $msg['content'] ='Live training新培训通知！ 培训名称：'.$data['name'].'；培训时间：'.$data['date'].' '.substr($data['start_time'],0,5).'-'.substr($data['end_time'],0,5).'；请您准时参加！';
            $time = strtotime($data['date'].' '.substr($data['start_time'],0,5)) - 1800;
            $redis = Yaf_Registry::get('redis');
            $redis->hset('Push',$time, json_encode(['users'=>$data['notify'],'llid'=>$llid]));
        }
        $model = new ModelModel;
        $dataAnnex = json_decode($data['annex'],true);
        $liveAnnex = json_decode($live['annex'],true);
        $del = array_diff($liveAnnex,$dataAnnex);
        if($del){
            foreach ($del as $v){
                $url = parse_url($v);
                $model->deleteImg($url['path']);
            }
        }
        $filePath = array_intersect($liveAnnex,$dataAnnex);
        if(!empty($data['path']) && !empty($data['file'])){
            $path = $data['path'];
            $file = $data['file'];
            $path = json_decode($path,true);
            $file = json_decode($file,true);
            if(count($path) && count($file)){
                foreach ($path as $k => $v){
                    $filePath[] = $model->moveImg($v,$file[$k],3);
                }
            }
        }
        unset($data['path']);
        unset($data['file']);
        $data['annex'] = json_encode(array_merge($filePath));


        Db::name('live_list')
            ->where(['id'=>$llid,'udid'=>$user['id'],'status'=>['in','1,3']])
            ->update($data);
        $msg['message'] = '修改成功';
        return $msg;
    }

    public function delAction($user,$llid)
    {
        $where['id'] =$llid;
        $where['fid'] =$user['fid'];
        $where['status'] =['in','1,3,9'];
        $del = Db::name('live_list')->where($where)->update(['status'=>0]);
        if($del){
            $msg['message'] = '课程删除成功';
        }else{
            $msg['message'] = '课程删除失败';
        }
        return$msg;
    }

    public function usersAction($user,$content = [])
    {
        if(empty($content['keywords'])){
            $where['fid']=$user['fid'];
            $where['status']=1;
            $data['lists'] = Db::name('users_detail')
                ->field('id as udid,phone,avatar,nickname,sex,section,duties')
                ->where($where)
                ->order('id desc')
                ->select();
        }else{
            $keywords = '%'.$content['keywords'].'%';
            $data['lists'] = Db::name('users_detail')
                ->field('id as udid,phone,avatar,nickname,sex,section,duties')
                ->where(['fid'=>$user['fid'],'phone|nickname|section|duties'=>['like',$keywords]])
                ->order('section asc')
                ->select();
        }

        $data['count'] = count($data['lists']);
        return $data;
    }

    public function sendSmsAction($content)
    {
        $live = Db::name('live_list')
            ->field('notify')
            ->where(['id'=>$content['llid'],'status'=>['in','1,3']])
            ->find();
        $phone = [];
        if($live){
            $userPhones = Db::name('users_detail')
                ->field('phone')
                ->where(['id'=>['in',$live['notify']],'status'=>1])
                ->select();
            foreach ($userPhones as $v){
                $phone[] = $v['phone'];
            }
        }
        $data['push']['phone'] = implode(',',$phone);
        $data['push']['content'] = $content['content'];
        $data['message'] = '短信已下发';
        return $data;
    }
}